package com.czk.utils;

import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/30 22:42
 */
public class KieSessionUtil {
    private KieSessionUtil() {

    }

    /**
     * 将xls文件转为str
     *
     * @param realPath
     * @return
     * @throws FileNotFoundException
     */
    public static String getDrl(String realPath) throws FileNotFoundException {
        // 例如：C:\\abc.xls
        File file = new File(realPath);
        InputStream is = new FileInputStream(file);
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);
        System.out.println(drl);
        return drl;
    }

    /**
     * kieSession与drlStr的整合
     *
     * @param drl
     * @return
     * @throws Exception
     */
    public static KieSession createKieSessionFromDrl(String drl) throws Exception {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) {
            List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
            for (Message message : messages) {
                System.out.println("Error: " + message.getText());
            }
            // throw new IllegalStateException("Compilation errors were found. Check the logs.");
        }
        return kieHelper.build().newKieSession();
    }

    /**
     * 获取session
     *
     * @param realPath
     * @return
     * @throws Exception
     */
    public static KieSession getKieSessionFromXls(String realPath) throws Exception {
        return createKieSessionFromDrl(getDrl(realPath));
    }
}
